TARGET ?= Permutations

# =================================================================
GCC ?= g++
SRC = $(shell ls $(TARGET).c* 2>/dev/null)
HEAD = $(shell ls $(TARGET).h* 2>/dev/null)
SHARED = lib$(TARGET).so
UT_SRC = $(TARGET)_unittest.cc
GIT_ROOT = $(shell git rev-parse --show-toplevel)
GTEST_ROOT = $(GIT_ROOT)/gtest

CFLAGS ?= -g -Wall -std=c++14
GTEST_MAIN ?= $(GTEST_ROOT)/googletest/src/gtest_main.cc
GTEST_INC ?= $(GTEST_ROOT)/googletest/include
GTEST_LIB ?= $(GTEST_ROOT)/build/lib
LDFLAGS += -I $(GTEST_INC)
LDFLAGS += -L $(GTEST_LIB) -L .
LDFLAGS += '-Wl,-rpath,$$ORIGIN'
LDFLAGS += -lgtest -pthread -l$(TARGET)

$(TARGET): $(SHARED) $(UT_SRC) $(GTEST_LIB)/libgtest.a $(GTEST_MAIN)
	$(GCC) -o $@ $(UT_SRC) $(GTEST_MAIN) $(CFLAGS) $(LDFLAGS)
	@ls -l $@

$(SHARED): $(SRC) $(HEAD)
	$(GCC) -o $@ --shared -fPIC $(CFLAGS) $<
	@ls -l $@

$(GTEST_LIB)/libgtest.a:
	[ -d $(GTEST_ROOT)/build ] || mkdir $(GTEST_ROOT)/build
	cd $(GTEST_ROOT)/build && cmake .. && make

.PHONY: clean test
clean:
	rm -rf $(TARGET) $(SHARED)

test: $(TARGET)
	./$(TARGET)
